<!-- FilePreview.vue -->
<template>
  <view class="file-preview">
    <template v-if="isImage">
      <wd-img 
        :width="100" 
        :height="100"  
        :src="cleanedUrl" 
        :enable-preview="true"
      />
    </template>
    <template v-else>
      <view class="file-item" @click="handleClick">
        <wd-icon name="file" size="24px" />
        <view class="file-info">
          <text class="file-name">{{ cleanedName }}</text>
          <!-- <text class="file-size">{{ formatFileSize(file.size) }}</text> -->
        </view>
      </view>
    </template>
  </view>
</template>

<script setup>
import { computed } from 'vue';

const props = defineProps({
  file: {
    type: Object,
    required: true
  }
});
const cleanedUrl = computed(() => {
  let url = props.file.url;
  // Split at first comma and take the first part
  if (url.includes(',')) {
    url = url.split(',')[0];
  }
  // Remove trailing } if present
  if (url.endsWith('}')) {
    url = url.slice(0, -1);
  }
  // Trim any whitespace
  return url.trim();
});
const cleanedName = computed(() => {
  if (props.file.name.endsWith('}')) {
    return props.file.name.slice(0, -1);
  }
  return props.file.name;
});
const emit = defineEmits(['download']);
const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'];

const fileExtension = computed(() => {
  const parts = cleanedName.value.split('.');
  return parts.length > 1 ? parts.pop()?.toLowerCase() : '';
});

const isImage = computed(() => fileExtension.value && imageExtensions.includes(fileExtension.value));
const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 Bytes';
  const k = 1024;
  const sizes = ['Bytes', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
};

const handleClick = () => {
  handleDownload(props.file)
};
const handleDownload = (file) => {
  uni.showModal({
    title: '下载确认',
    content: `确定要下载文件 ${cleanedName.value}  吗？`,
    success: (res) => {
      if (res.confirm) {
        downloadFile(file);
      }
    }
  });
};

const downloadFile = (file) => {
  uni.showLoading({
    title: '下载中...'
  });
  
  uni.downloadFile({
    url: cleanedUrl.value,
    success: (res) => {
      if (res.statusCode === 200) {
        uni.saveFile({
          tempFilePath: res.tempFilePath,
          success: (saveRes) => {
            uni.hideLoading();
            uni.showToast({
              title: '下载成功',
              icon: 'success'
            });
            console.log('文件保存路径:', saveRes.savedFilePath);
          },
          fail: () => {
            uni.hideLoading();
            uni.showToast({
              title: '保存文件失败',
              icon: 'error'
            });
          }
        });
      }
    },
    fail: () => {
      uni.hideLoading();
      uni.showToast({
        title: '下载失败',
        icon: 'error'
      });
    }
  });
};

</script>

<style scoped>
.file-preview {
  margin: 8px 0;
}

.file-item {
  display: flex;
  align-items: center;
  padding: 8px;
  border: 1px solid #eee;
  border-radius: 4px;
  cursor: pointer;
}

.file-item:hover {
  background-color: #f5f5f5;
}

.file-info {
  margin-left: 8px;
  display: flex;
  flex-direction: column;
}

.file-name {
  font-size: 14px;
  color: #333;
  margin-bottom: 4px;
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.file-size {
  font-size: 12px;
  color: #999;
}
</style>